package com.system.service.impl;

import com.system.mapper.RolesMapper;
import com.system.mapper.UsersMapper;
import com.system.pojo.Roles;
import com.system.pojo.Users;
import com.system.service.RolesService;
import com.system.util.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("roleService")
public class RolesServiceImpl implements RolesService {
    JSONUtil jsonUtil = new JSONUtil();
    @Autowired
    private RolesMapper rolesMapper;
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public List<Roles> select(Roles roles) {
        return rolesMapper.select(roles);
    }

    @Override
    public String insert(Roles roles) {
        return jsonUtil.toJson("0", rolesMapper.insert(roles), "");
    }

    @Override
    public String update(Roles roles) {
        return jsonUtil.toJson("0", rolesMapper.update(roles), "");
    }

    @Override
    public String delete(String id) {
        System.out.println("删除角色，ID：" + id);
        try {
            Users users = new Users();
            users.setRole(id);
            List<Users> userss = usersMapper.select(users);
            if (userss.size() > 0 && userss != null) {
                return jsonUtil.toJson("1", "", "角色下有用户，不能删除！");
            } else {
                return jsonUtil.toJson("0", rolesMapper.delete(id), "");
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            return jsonUtil.toJson("0", rolesMapper.delete(id), "");
        }
    }

    @Override
    public String insertRoleMenus(List<Roles> roless) {
        Roles roles = new Roles();
        List<String> menus = new ArrayList<>();
        for (int i = 0; i < roless.size(); i++) {
            roles.setId(roless.get(i).getId());
            menus.add(roless.get(i).getMenus());
        }
        String menu = menus.toString().replace("[", "");
        menu = menu.replace("]", "");
        roles.setMenus(menu);
        System.out.println("保存角色菜单权限，ID：" + roles.getId() + "菜单ID：" + roles.getMenus());
        int s = -1;
        try {
            s = rolesMapper.update(roles);
            return jsonUtil.toJson("0", s, "");
        } catch (Exception e) {
            System.out.println(e.toString());
            return jsonUtil.toJson("0", 0, e.toString());
        }
    }

    public RolesMapper getRolesMapper() {
        return rolesMapper;
    }

    public void setRolesMapper(RolesMapper rolesMapper) {
        this.rolesMapper = rolesMapper;
    }
}
